<script setup lang="ts">
import { reactive, ref } from 'vue';
import { DeleteOutlined, } from '@ant-design/icons-vue';
import { useMessage } from '/@/hooks/web/useMessage';
import { Icon } from '/@/components/Icon';
import BatchAthorizeModal from './BatchAthorizeModal.vue'
import UserAuthAppModal from './UserAuthAppModal.vue'
import { GetAllAppReq, GetAllMangersReq, RemoveBindManagersToAppReq } from '/@/api/managerAuthorize'

const { createMessage } = useMessage();
// search bar
const searchFormRef = ref();
const searchFrom = reactive({
  username: '',
  mobile: '',
  email: '',
  appId: undefined,
});
const searchFormActions = {
  reset() {
    currentSelectedClient.value = undefined;
    searchFrom.appId = undefined;
    searchFormRef.value.resetFields();
    tableActions.getList();
  },
  ok() {
    pgActions.reset();
    tableActions.getList();
  }
}

const pg = reactive({
  current: 1,
  size: 10,
  total: 0
})
const pgActions = {
  reset() {
    pg.current = 1;
    pg.size = 10;
    pg.total = 0;
  },
  currentChange(c) {
    pg.current = c;
    tableActions.getList();
  }
}

const table = reactive({
  data: [],
  selected: [],
  loading: false
})
const tableActions = {
  async getList() {
    table.loading = true;
    let params = {
      startIndex: pg.current,
      pageSize: pg.size,
      clientId: searchFrom.appId,
      username: searchFrom.username,
      email: searchFrom.email,
      mobile: searchFrom.mobile,
    };
    let { data, respCode, } = await GetAllMangersReq(params);
    table.loading = false;
    if (respCode === 200) {
      table.data = data.list;
      pg.total = data.total;
      table.selected = [];
    }
  },
  delete(r) {
    tableActions.removeBatch([r.userId])
  },
  batchDelete() {
    let ids = table.selected.map((e: any) => e.userId);
    tableActions.removeBatch(ids)
  },
  async removeBatch(ids: any[]) {
    const { respCode, respMsg } = await RemoveBindManagersToAppReq({
      id: searchFrom.appId,
      administratorIds: ids
    });
    if (respCode == 200) {
      createMessage({
        message: respMsg,
      });
      tableActions.getList();
    }
  },
  update(r) {
    modal1.data = r;
    modal1Actions.show();
  },
  selectionChange(selections) {
    table.selected = selections;
  }
}

// app list
const applist = ref([]);
const getAllApp = async () => {
  const { data, respCode } = await GetAllAppReq({ clinetName: '' });
  if (respCode == 200) {
    applist.value = data.map(e => ({
      ...e,
      slots: { title: 'custom' }
    })) || [];
  }  
}
getAllApp();

let currentSelectedClient = ref()
const selectAppHandler = (key) => {
  currentSelectedClient.value = key;
  if (key) {
    searchFrom.appId = key.id;
  }
  searchFormActions.ok();
}
const bindManagers = (appId) => {
  modal.appId = appId + '';
  modalActions.show();
}

// batch bind modal
const modal = reactive({
  visible: false,
  appId: ''
})
const modalActions = {
  show() {
    modal.visible = true;
  },
  success() {
    tableActions.getList();
  }
}

const modal1 = reactive({
  visible: false,
  data: undefined as any
})
const modal1Actions = {
  show() {
    modal1.visible = true;
  },
  success() {
    tableActions.getList();
  }
}

tableActions.getList();
const resetClient = () => {
  currentSelectedClient.value = undefined;
  searchFrom.appId = undefined;
  tableActions.getList()
}


</script>

<template>
  <div class="p-4 manager-authorize">
    <div class="searchBox">
      <el-form :model="searchFrom" ref="searchFormRef" inline :label-col="80">
        <el-form-item prop='username' label="用户名">
          <el-input v-model="searchFrom.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item prop='mobile' label="手机号">
          <el-input v-model="searchFrom.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item prop='email' label="邮箱">
          <el-input v-model="searchFrom.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchFormActions.ok">查询</el-button>
          <el-button @click="searchFormActions.reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="middle-content">
      <el-tree class='group-tree' :data="applist" node-key="id" @node-click="selectAppHandler">
        <template #default="{ data }">
          <div class="flex-auto flex justify-between items-center">
            <span style="flex: 1;overflow: hidden; white-space: nowrap; text-overflow: ellipsis;">{{ data.clientName }}</span>
            <Icon icon="gg:import" @click.stop='bindManagers(data.id)' style='flex: 14px 0 0; margin-left: 15px;'/>
          </div>
        </template>
      </el-tree>
      <div class="userTable">
        <div class="flex justify-between items-center mb-4">
          <span>当前应用：<el-tag type="success" :closable="!!currentSelectedClient" @close="resetClient">{{currentSelectedClient ? currentSelectedClient.clientName : '全部'}}</el-tag></span>
          <el-popconfirm title="确定要通过吗？" confirm-button-text="确定" cancel-button-text="取消" @confirm="tableActions.batchDelete">
            <template #reference>
              <el-button type="primary" :loading="table.loading" :disabled="!table.selected.length || !searchFrom.appId">
                <DeleteOutlined class='mr-1'/>批量移除
              </el-button>
            </template>
          </el-popconfirm>
        </div>
        <el-table class="mb-4" v-loading="table.loading"  :data="table.data" row-key="userId"
          @selection-change="tableActions.selectionChange">
          <el-table-column type="selection" width="55" fixed />
          <el-table-column prop="username" label="用户名" fixed></el-table-column>
          <el-table-column prop="mobile" label="手机号"></el-table-column>
          <el-table-column prop="email" label="邮箱"></el-table-column>
          <el-table-column prop="operation" label="操作">
            <template #default="scope" v-if='searchFrom.appId'>
              <el-button link type="primary" @click="tableActions.delete(scope.row)">移除授权</el-button>
              <el-button link type="primary" @click="tableActions.update(scope.row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination class="flex justify-end" background layout="prev, pager, next" :total="pg.total"
          :current-page="pg.current" :page-size="pg.size" @current-change="pgActions.currentChange"></el-pagination>
      </div>
    </div>
    <BatchAthorizeModal :appId='modal.appId' v-model:visible="modal.visible" @success='modalActions.success' />
    <UserAuthAppModal :appOptions='applist' v-model:visible="modal1.visible" :data="modal1.data" @success='modal1Actions.success' />
  </div>
</template>

<style lang="less" scoped>
html[data-theme='light'] {
  .searchBox {
    background-color: #fff;
  }

  .middle-content {
    background-color: #fff;
  }
}

html[data-theme='dark'] {
  .searchBox {
    background-color: #000;
  }

  .middle-content {
    background-color: #000;
  }
}

.manager-authorize {

  .searchBox {
    margin-bottom: 20px;
    padding: 10px 10px 0;
  }

  .middle-content {
    padding: 15px;
    display: flex;
    height: calc(100vh - 80px - 2rem - 72px);

    .group-tree {
      height: calc(100% - 80px);
      overflow: hidden auto;
      flex: 0 0 250px;
      margin: 40px 0;
      padding: 0 15px;
      margin-right: 40px;

      .inTree {
        display: flex;
        justify-content: space-between;
      }
    }

    .userTable {
      flex: 1;
      width: 0;
    }

  }

  :deep(.el-tree-node__label) {
    flex: 1;
    width: 0;
  }

}
</style>